package com.tms.warehouse.mappings;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.tms.warehouse.Warehouse;
import com.tms.warehouse.entity.Rack;
import com.tms.warehouse.entity.Shelf;

public class ShelfMapper extends AbstractMapper<Shelf> {

	private static final String ENTITY_NAME = "Shelf";
	private static final String PROPERTY_NAME = "name";
	private static final String PROPERTY_NUMBER = "number";
	private static final String PROPERTY_RACK = "rack";

	@Override
	public String getType() {

		return ENTITY_NAME;
	}

	@Override
	public Shelf wrap(Entity entity) {

		String name = (String) entity.getProperty(PROPERTY_NAME);
		long number = (Long) entity.getProperty(PROPERTY_NUMBER);
		long id = entity.getKey().getId();
		Key rackKey = (Key) entity.getProperty(PROPERTY_RACK);
		Rack rack = rackKey == null ? null : Warehouse.findRackById(String
				.valueOf(rackKey.getId()));
		return new Shelf(id, name, (int) number, rack);
	}

	@Override
	public Entity unwrap(Shelf entity) {

		Entity shelf;
		if(entity.getId() > 0) {
			shelf = new Entity(createKey(entity.getId()));
		} else {
			shelf = new Entity(ENTITY_NAME);			
		}
		shelf.setProperty(PROPERTY_NAME, entity.getName());
		shelf.setProperty(PROPERTY_NUMBER, entity.getNumber());
		shelf.setProperty(PROPERTY_RACK,
				super.mapRelation(entity.getRack(), new RackMapper()));
		return shelf;
	}

}
